package com.mate.cloud.auth.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.mate.cloud.auth.domain.UmsAdmin;
import com.mate.cloud.auth.domain.UmsResource;
import com.mate.cloud.auth.dto.UpdateAdminPasswordParam;
import com.mate.cloud.auth.exception.AuthBusinessRuntimeException;
import com.mate.cloud.auth.exception.UserExceptionEnumCode;
import com.mate.cloud.auth.mapper.UmsAdminMapper;
import com.mate.cloud.auth.service.UmsAdminService;
import com.mate.cloud.auth.service.UmsResourceService;
import com.mate.cloud.auth.utils.SecurityUtils;
import com.mate.cloud.cache.service.RedisCacheService;
import com.mate.cloud.core.common.constant.CommonConstants;
import com.mate.cloud.core.util.JwtGeneratorUtil;
import com.mate.cloud.core.util.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: java类作用描述
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2024/6/14 21:32
 * @updateUser: MI
 * @updateTime: 2024/6/14 21:32
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Slf4j
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {

    @Resource
    private UmsResourceService umsResourceService;


    @Resource
    private RedisCacheService redisCacheService;


    @Resource
    private UmsAdminMapper umsAdminMapper;

    // 用于记录 token 及其刷新时间
    private static final Map<String, Long> tokenRefreshTimes = Maps.newConcurrentMap();

    private static final long REFRESH_INTERVAL = 1000 * 60 * 30; // 30 分钟

    @Override
    public UmsAdmin getAdminByUsername(String username) {
        UmsAdmin umsAdmin = getUmsAdmin(username);

        return umsAdmin;
    }

    /**
     * 根据用户名修改登录时间
     */
    private void updateLoginTimeByUsername(String username) {
        final UmsAdmin umsAdmin = getUmsAdmin(username);
        if (umsAdmin == null) return;

        umsAdmin.setLoginTime(new Date());
        umsAdminMapper.updateById(umsAdmin);
    }

    private UmsAdmin getUmsAdmin(String username) {
        LambdaQueryWrapper<UmsAdmin> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UmsAdmin::getUsername, username);
        queryWrapper.eq(UmsAdmin::getStatus, 0);
        queryWrapper.last(CommonConstants.LIMIT_ONE);
        return umsAdminMapper.selectOne(queryWrapper);
    }

    @Override
    public String refreshToken(String paramToken) {
        if (paramToken == null || paramToken.isEmpty()) {
            log.warn("Token refresh failed: Token is empty");
            throw new AuthBusinessRuntimeException(UserExceptionEnumCode.TOKEN_NOT_EMPTY.getCode());
        }
        // token 截取
        String token = SecurityUtils.getToken(paramToken);

        if (StringUtils.isNotEmpty(token) && JwtGeneratorUtil.validateToken(token)) {
            return JwtGeneratorUtil.refreshAccessToken(token);
        } else {
            // 1、解析token
            DecodedJWT decodedJWT = JwtGeneratorUtil.decodeToken(token);
            if (decodedJWT != null) {
                // 如果token在30分钟之内刚刷新过，返回原token
//                final String newToken = tokenRefreshJustBefore(paramToken, refreshToken);
                final String username = decodedJWT.getSubject();
                return JwtGeneratorUtil.generateAccessToken(username);
            }
        }
        return null;
    }

    @Override
    public int updatePassword(UpdateAdminPasswordParam updatePasswordParam) {
        return 0;
    }


    @Override
    public List<UmsResource> getResourceList(Integer adminId) {
        return umsResourceService.getResourceList(adminId);
    }

}
